#!/bin/bash
# Install script for ubuntu based linux.

TMP=/tmp
CWD="`dirname $0`"
LOG=$TMP/aries-emacs.log
DOT_EMACS=$CWD/dot.emacs
HOME_EMACS=$HOME/.emacs

# Emacs version
VERSION=23

# Dependents libraries or addons

DEPENDENTS="emacs$VERSION-el cscope cscope.el"
# CEDET downloaded from http://cedet.sourceforge.net which
# fully compatible with emacs23

CEDET_TAR="cedet-1.1.tar.gz"
CEDET="cedet-1.1"

ECB_ZIP="ecb-2.40.zip"
ECB="ecb-2.40"

AC_COMPLETE_TAR="auto-complete-1.3.1.tar.bz2"
AC_COMPLETE="auto-complete-1.3.1"

# Don't need anymore
# SR_SPEEDBAR downloaded from www.emacswiki.org/emacs/download/sr-speedbar.el
#SR_SPEEDBAR="sr-speedbar.el"

# Create log file
CreateLog()
{
	rm $LOG && touch $LOG
}

# Install dependents
InstallDep()
{
	for i in $DEPENDENTS; do
		echo -e "Installing emacs addon: $i"
		sudo apt-get install $i >> $LOG
		if [ $? -ne 0 ]; then
			echo -e "ERROR: failed to install package: $i"
			exit 1
		fi
	done

	if [ ! -f $CWD/$CEDET_TAR ]; then
		echo -e "ERROR: Can't locate $CEDET_TAR at $CWD"
		exit 1
	fi

	OLD_PWD="`pwd`"				# Will be restored after
	echo -e "Installing CEDET"
	if [ ! -d $CWD/$CEDET ]; then
		tar -zxf $CWD/$CEDET_TAR
	fi
	cd $CWD/$CEDET
	make EMACS=emacs$VERSION >> $LOG 2>&1
	cd $OLD_PWD
	if [ -d $HOME/cedet ]; then
		rm $HOME/cedet.bak >& /dev/null
		mv $HOME/cedet $HOME/cedet.bak
	fi
	cp -r $CWD/$CEDET $HOME/cedet

	echo -e "Installing ECB"
	if [ ! -d $CWD/$ECB ]; then
		unzip $CWD/$ECB_ZIP >> $LOG 2>&1
	fi
	cd $CWD/$ECB
	# Patch the version check for cedet
	sed -i "s/1 0 4 9/1 1 4 9/" ecb-upgrade.el
	make CEDET=$HOME/cedet >> $LOG 2>&1
	cd $OLD_PWD
	if [ -d $HOME/ecb ]; then
		rm $HOME/ecb.bak >& /dev/null
		mv $HOME/ecb $HOME/ecb.bak
	fi
	cp -r $CWD/$ECB $HOME/ecb

	echo -e "Installing auto-complete"
	if [ ! -d $CWD/$AC_COMPLETE ]; then
		tar -jxf $CWD/$AC_COMPLETE_TAR
	fi
	cd $CWD/$AC_COMPLETE
	make EMACS=emacs$VERSION >> $LOG 2>&1
	cd $OLD_PWD
	if [ -d $HOME/auto-complete ]; then
		rm $HOME/auto-complete.bak >& /dev/null
		mv $HOME/auto-complete $HOME/auto-complete.bak
	fi
	cp -r $CWD/$AC_COMPLETE $HOME/auto-complete
	
	#cp -r $CWD/$SR_SPEEDBAR $HOME/cedet/
}

# Install .emacs
InstallDotEmacs()
{
	if [ ! -f $DOT_EMACS ]; then
		echo -e "ERROR: can't locate dot_emacs at $CWD"
		exit -1
	fi

	if [ -f $HOME_EMACS ]; then
		echo -e "Backing $HOME_EMACS to $HOME_EMACS.bak"
		mv $HOME_EMACS $HOME_EMACS.bak
		echo -e "Installing $DOT_EMACS to $HOME_EMACS"
		cp $DOT_EMACS $HOME_EMACS
	fi
}


##################################################################
# Start of program
##################################################################
CreateLog
#InstallDep
InstallDotEmacs
